# encoding:utf-8
import sys
import re
import string
import xlrd
import xlwt
import time
import os
import stat
import subprocess

ee_dict = dict()
se_dict = dict()

enter_mark = 'ENTER'
exit_mark = 'EXIT'
start_mark = 'START'
end_mark = 'END'
time_mark = ' TIME]'

# 定义搜索字段的正则表达式
pattern_time = re.compile(r'(\d{2}):(\d{2}):(\d{2}).(\d{3})')
pattern_enter = re.compile(r'\[ENTER .+ TIME\]')
pattern_exit = re.compile(r'\[EXIT .+ TIME\]')
pattern_start = re.compile(r'\[START .+ TIME\]')
pattern_end = re.compile(r'\[END .+ TIME\]')

ee_mark = [enter_mark, exit_mark]
se_mark = [start_mark, end_mark]


# 把字符串时间转化为float
def cal_duration_time(start, end):
    # print "start : %s end : %s" %(start ,end)
    _start1 = start.split(':')
    _start2 = _start1[2].split('.')
    t_start = 1000 * (long(_start1[0]) * 3600 + long(_start1[1]) * 60 + long(_start2[0])) + long(_start2[1])

    _end1 = end.split(':')
    _end2 = _end1[2].split('.')
    t_end = 1000 * (long(_end1[0]) * 3600 + long(_end1[1]) * 60 + long(_end2[0])) + long(_end2[1])
    return (t_end - t_start) / 1000.0


# 根据提取的字段计算时间差
def statistics_duration_time(time_dict):
    dict_len = len(time_dict)
    # print "Length : %d" % dict_len
    if dict_len:
        for k, v in time_dict.iteritems():
            index = 1
            dur_time_list = []
            global MAX_COL
            if len(v) > MAX_COL:
                MAX_COL = len(v)
            while index < len(v):
                dur_t = cal_duration_time(v[index][0], v[index][1])
                dur_time_list.append(dur_t)
                index += 1
            write_duration_time(k, dur_time_list)


# 根据正则匹配每一行，并存储匹配的字段
def search_info(time_dict, pattern_type, mark, index):
    info = pattern_type.search(log_line)
    if info:
        info_str = info.group()
        # print "----- %s " %info_str
        info_str = info_str.replace('[' + mark[index] + ' ', '')
        info_str = info_str.replace(time_mark, '')
        time_str = pattern_time.search(log_line).group()
        info_str = info_str.rstrip().lstrip()
        if time_dict.has_key(info_str):
            if mark[index] == start_mark or mark[index] == enter_mark:
                time_dict[info_str].append([time_str])
                time_dict[info_str][0] += 1
            elif mark[index] == end_mark or mark[index] == exit_mark:
                time_dict[info_str][time_dict[info_str][0]].append(time_str)
        else:
            print "Detected %s: " % info_str
            iterm = {info_str: [1, [time_str]]}
            time_dict.update(iterm)


# 检查提取的log是否有效
def check_dict(time_dict):
    tkeys = list(time_dict.keys())
    for key in tkeys:
        value_index = 1;
        while value_index < len(time_dict[key]) and len(time_dict[key]) >= 2:
            if len(time_dict[key][value_index]) != 2:
                # print "Detected [%s] log incomplete Delete: %s " %(key,time_dict[key][value_index])
                del time_dict[key][value_index]
                time_dict[key][0] -= 1
            else:
                value_index += 1
        if len(time_dict[key]) < 2:
            print "Detected [%s] log incomplete " % key
            del (time_dict[key])


# 把统计到的时间填到excel表中
def write_duration_time(key, list):
    dict_len = len(list)
    index = 0
    # print "Length : %d" % dict_len
    global SHEET_LINE_NUM
    if dict_len:
        average_t = sum(list) / dict_len
        sheet.write(SHEET_LINE_NUM, 0, key, common_style)
        sheet.write(SHEET_LINE_NUM, 1, str(min(list)) + "~" + str(max(list)), common_style)
        sheet.write(SHEET_LINE_NUM, 2, float('%0.3f' % average_t), common_style)
        sheet.write(SHEET_LINE_NUM, 3, dict_len, common_style)
    while index < dict_len:
        sheet.write(SHEET_LINE_NUM, index + 4, list[index], common_style)
        index += 1
    SHEET_LINE_NUM += 1


if __name__ == "__main__":
    print "1. Start catch log "
    print "2. Stop catch log,Generate xls \n "
    select = input("Please select 1 or 2 : ")

    if select == 1:
        subprocess.call('adb root', shell=True)
        subprocess.call('adb remount', shell=True)
        subprocess.call('adb shell setenforce 0', shell=True)

        # 存储log命令到文件中，并在手机中执行
        f_temp = open('dcslogcat.sh', 'w')

        f_temp.write('logcat -v time > /sdcard/time_test.log & ')
        f_temp.close()

        os.chmod('dcslogcat.sh', stat.S_IRWXU | \
                 stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | \
                 stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH)

        subprocess.call('adb push dcslogcat.sh /system/bin/ &', shell=True)
        subprocess.call('adb shell dcslogcat.sh ', shell=True)
        # runshell=subprocess.Popen('adb shell dcslogcat.sh ', shell=True)
        ps_ret = subprocess.Popen('adb shell ps |grep logcat', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                  shell=True)
        logcatpid = ps_ret.stdout.readline()

        if len(logcatpid) == 0:
            print "Start logcat failed \n"
            print u"请手动在shell命令行中输入一下命令："
            print "logcat -v time > /sdcard/time_test.log & \n"
            subprocess.call('adb shell', shell=True)

        else:
            print logcatpid
            print "Start logcat success"
    elif select == 2:
        subprocess.call('adb root', shell=True)
        subprocess.call('adb remount', shell=True)
        dir_dt = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        subprocess.call('mkdir ' + dir_dt, shell=True)
        print "\nPull time_test.log ..."
        ret = subprocess.call('adb pull /sdcard/time_test.log ' + dir_dt, shell=True)

        ps_ret = subprocess.Popen('adb shell ps |grep logcat', stdout=subprocess.PIPE, shell=True)
        logcatpid = ps_ret.stdout.readline()
        if len(logcatpid) > 0:
            logcatpid = logcatpid[10:15]
            print '\nLogcat PID: ' + logcatpid
            subprocess.call('adb shell kill ' + logcatpid, shell=True)
        subprocess.call('adb shell rm  /sdcard/time_test.log', shell=True)

        if ret == 0:
            global SHEET_LINE_NUM
            SHEET_LINE_NUM = 0
            global MAX_COL
            MAX_COL = 0;

            print "\nStart analyze log \n"
            flog = open(dir_dt + '/time_test.log')
            log_line = flog.readline()
            while log_line:
                search_info(ee_dict, pattern_enter, ee_mark, 0)
                search_info(ee_dict, pattern_exit, ee_mark, 1)
                search_info(se_dict, pattern_start, se_mark, 0)
                search_info(se_dict, pattern_end, se_mark, 1)
                log_line = flog.readline()

            check_dict(ee_dict)
            check_dict(se_dict)

            common_style = xlwt.easyxf(
                'font: height 300,name Arial Rounded MT Bold,colour_index black, bold off,italic off;align: wrap on,vert centre,horiz left;')
            ftable = xlwt.Workbook(encoding='utf-8')
            sheet = ftable.add_sheet('sheet1', cell_overwrite_ok=True)
            style = xlwt.XFStyle()
            font = xlwt.Font()
            sheet.col(0).width = 256 * 50
            sheet.col(1).width = 256 * 25
            sheet.col(2).width = 256 * 20
            sheet.col(3).width = 256 * 15

            sheet.write(0, 0, '测试函数', common_style)
            sheet.write(0, 1, '时间范围', common_style)
            sheet.write(0, 2, '平均时间', common_style)
            sheet.write(0, 3, '统计次数', common_style)
            SHEET_LINE_NUM += 1

            statistics_duration_time(ee_dict)
            statistics_duration_time(se_dict)

            col_index = 0;
            while col_index < MAX_COL - 1:
                sheet.col(col_index + 4).width = 256 * 10
                sheet.write(0, col_index + 4, "第" + str(col_index + 1) + '次', common_style)
                col_index += 1
            # print "col_index: %d" %col_index
            print "\nDetected %d valid node \n" % (SHEET_LINE_NUM - 1)
            if (SHEET_LINE_NUM - 1) == 0:
                print "Invalid log file \n"
            else:
                tablename = 'DcsTimeTest' + dir_dt + '.xls'
                print "Generated :%s\%s \n" % (dir_dt, tablename)
                ftable.save(dir_dt + "/" + tablename)
            flog.close()
            print "End ..."
        else:
            print "cant not find /sdcard/time_test.log"
    else:
        print "select error try again"
    os.system("pause")

